package com.blb.seckill.listener;

import com.alibaba.fastjson.JSON;
import com.blb.seckill.config.RabbitMQConfig;
import com.blb.seckill.entity.SeckillOrder;
import com.blb.seckill.service.SeckillOrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 处理异步下单的监听器（可以放到单独服务中）
 */
@Slf4j
@Component
public class HandleSeckillOrderListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitListener(queues = RabbitMQConfig.QUEUE_SECKILLORDER)
    public void receiveSeckillOrderMessage(String json, Channel channel, Message message){
        log.info("收到异步下单消息：{}",json);
        try {
            channel.basicQos(300);
            SeckillOrder seckillOrder = JSON.parseObject(json, SeckillOrder.class);
            boolean result = seckillOrderService.createOrder(seckillOrder);
            if(result){
                //发送确认消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }else{
                //返回失败通知
                //第一个true所有消费者都会拒绝这个消息，false代表只有当前消费者拒绝
                //第二个true当前消息会进入到死信队列，false重新回到原有队列中，默认回到头部
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
